Skip to main content

Common Web Attacks

TOC​

Cross Site Scripting (XSS)​

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user.

-- OWASP

As state by OWASP definition, XSS takes place when malicious code is injected. Thus, rule of thumb to prevent XSS is : NEVER TRUST USER INPUTS.

Types of XSS​

XSS attacks can generally be categorized into three categories: reflected, stored and DOM-based, while first two are more common.

  • Reflected XSS (Non-persistent / Type-I):

    This is the most common type of XSS attack, where the injected script is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request.

  • Stored XSS (Persistent / Type-II):

    This type of XSS occurs when the injected script is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information.

  • Dom-Based XSS (Type-0):

    This type of XSS is less known, where the attack payload is executed as a result of modifying the DOM “environment” in the victim’s browser used by the original client side script, so that the client side code runs in an “unexpected” manner

TypePersistentFlaw LocationExamples
Reflected❌ServerIncluding malicious script in get request url parameters
Stored✅ServerInject malicious script in comment fields and sent back to database, triggered when user loads webpage
Dom-Based❌Client (Browser)Client-side scripts write data provided by the user to the DOM

How to prevent ?​

While major frameworks (such as React) does provide XSS prevention by default, they still might be vulnerability and building a mindset of preventing XSS is still beneficial.

Multiple preventions are available to prevent XSS, but it can hardly be solved by any single prevention techniques. Thus, having a deep understand of where inputs are accepted and how they are used in the application, then combine multiple techniques accordingly might be the best practice.

Output Encoding​

  • Do not trust user inputs. Whenever user input might be used to display on the UI, always consider encoding the input string to avoid XSS.

HTML Sanitization​

Content Security Policy (CSP)​

Refer to CSP note.

Trusted Types​

  • Trusted Types API is a browser API that gives web developers a way to lock down the insecure parts of the DOM API to prevent XSS attacks.

Third-Party Libraries​

  • Some third-party libraries can be utilized to prevent XSS, such as DOMPurify and js-xss.
Recommend Readings

Cross Site Request Forgery (CSRF)​

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated.

-- OWASP

How to prevent ?​

  • CSRF Token
  • SameSite Cookies
  • Referer-based validation

Open Redirect​

An open redirect (CWE-601) happens when an application redirects users to a URL taken from untrusted input without checking that the target is on its own site. The link the victim clicks looks legitimate because it starts with the trusted domain, but the browser ends up on an attacker-controlled page. A common use is phishing, e.g. a fake "please sign in again" page.

A typical place this shows up is the post-login redirect: the app remembers the page the user was trying to open, sends them to log in, then sends them back. Since the return URL comes from the request, it must be validated as a same-site path before redirecting.

// 1. Not logged in: remember where the user wanted to go
function requireLogin(req, res, next) {
if (req.user) return next();
res.cookie('return_to', req.originalUrl, { httpOnly: true });
res.redirect('/login');
}

// 2. Login succeeded: send the user back
app.get('/login/callback', (req, res) => {
// ...complete login...
res.redirect(getSafeRedirect(req.cookies.return_to, ORIGIN));
});

Bypass: Validate Before Normalizing​

A validator that looks reasonable but is vulnerable:

function getSafeRedirect(input, origin) {
const decoded = decodeURIComponent(input);
// Block absolute URLs, protocol-relative URLs, backslashes and CR/LF
if (!decoded.startsWith('/') || /^\/\/|\\|[\r\n]/.test(decoded)) return '/';

const u = new URL(decoded, origin);
if (u.origin !== origin) return '/';
return u.pathname + u.search + u.hash;
}

new URL() performs dot-segment normalization: the path is split on /, and each .. segment removes the segment before it. The WHATWG URL Standard also treats %2e%2e as ... So the string checked by the regex is not the string that gets returned.

Payload: /%252e%252e//evil.com

StepValueNotes
Victim clicks link/%252e%252e//evil.comDouble-encoded, the browser and server keep it as-is
Stored as return URLSame as aboveDoesn't look like an absolute URL, so it's saved
Decoded once/%2e%2e//evil.comStarts with /%, passes the ^// check
new URL() normalizespathname = //evil.comSee below
Origin checkPassesA relative path is resolved against the site's own origin
ResponseLocation: //evil.comBrowser treats it as https://evil.com and leaves the site

How normalization produces //: splitting the path gives three segments: %2e%2e, an empty string (nothing between the two slashes), and evil.com. Since .. is already at the root, there's no previous segment to remove, so it only drops itself. What remains is "empty segment + evil.com", which serializes to //evil.com. The .. segment was shielding the // behind it, and normalization removed the shield.

Why double encoding: if the attacker sends /%2e%2e//evil.com directly, the browser normalizes it before sending the request, the server receives //evil.com, and the regex blocks it. One extra layer of encoding survives the browser and the server framework, and only becomes a dot segment after the validator decodes it.

Other variants that end up as //evil.com after decoding + normalization: uppercase %252E%252E, mixed .%252e, and /a/..//evil.com. Triple encoding (%25252e) stays literal after a single decode, so it doesn't trigger.

How to prevent ?​

  • Validate the normalized output. After parsing, the result must start with exactly one /. This alone closes the bypass above.
  • Don't decode the input. decodeURIComponent is the root cause, and it also breaks legitimate URLs: /search?q=a%26b becomes ?q=a&b after decoding, splitting one parameter into two. The request URL is already a valid encoded URL, so pass it straight to new URL(). Then %252e always stays literal and this class of attack disappears at the source.
  • Fail closed. Any parse error should fall back to '/'. This matters especially if you do decode: decodeURIComponent('/%E0%A4%A') throws a URIError, and since the attacker controls the input, an uncaught error turns into a 500.
  • Validate on write too. Run the same check before storing the return URL, so a malicious value is never recorded. Not strictly necessary, but cheap.
  • Test an invariant, not just payloads. Besides the variants above (uppercase, mixed encoding, multiple ..), assert that the returned value, when resolved by a browser, is always same-origin.

Backslash variants such as /\evil.com are covered by the origin check: WHATWG treats \ as / for http(s) URLs, so it parses as a protocol-relative URL to evil.com.

function getSafeRedirect(input, origin) {
if (typeof input !== 'string' || !input.startsWith('/')) return '/';
try {
const u = new URL(input, origin); // no decodeURIComponent
if (u.origin !== origin) return '/';
const out = u.pathname + u.search + u.hash;
return (out.startsWith('/') && !out.startsWith('//')) ? out : '/';
} catch {
return '/';
}
}
Lesson

Validate the value you will actually use. If the input still goes through decoding, normalization or parsing after validation, validate again after that transformation, otherwise the transformation can turn a harmless input into a dangerous one.

References​